package com.kayo.specimen.resolver;

import com.kayo.specimen.annotion.PagingParam;
import com.kayo.specimen.utility.PagingInfo;
import com.kayo.specimen.utility.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class PagingParamResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(PagingParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        PagingParam parameterAnnotation = parameter.getParameterAnnotation(PagingParam.class);
        PagingInfo pagingInfo = new PagingInfo(parameterAnnotation.page(),
                parameterAnnotation.limit(), parameterAnnotation.sort(), parameterAnnotation.order());

        String page = webRequest.getParameter("page");
        if (!StringUtils.isNullOrEmpty(page))
            pagingInfo.setPage(Integer.parseInt(page));

        String limit = webRequest.getParameter("limit");
        if (!StringUtils.isNullOrEmpty(limit))
            pagingInfo.setLimit(Integer.parseInt(limit));

        String sort = webRequest.getParameter("sort");
        if (!StringUtils.isNullOrEmpty(sort))
            pagingInfo.setSort(sort);

        String order = webRequest.getParameter("order");
        if(!StringUtils.isNullOrEmpty(order))
            pagingInfo.setOrder(order);

        return pagingInfo;
    }
}
